<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-select
            clearable
            v-model="formSearch.type"
            placeholder="请选择用户状态"
          >
            <el-option label="正常" value="1"> </el-option>
            <el-option label="已封号" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formSearch.name"
            placeholder="搜索用户名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formSearch.phone"
            placeholder="搜索手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <!-- <el-button icon="el-icon-plus" type="primary" @click="handleAdd" v-show="permission.add">新增用户</el-button> -->
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column prop="petName" label="用户名称"></el-table-column>
        <el-table-column
          prop="phone"
          :show-overflow-tooltip="tooltip"
          label="手机号"
        ></el-table-column>
        <el-table-column
          prop="typeName"
          :show-overflow-tooltip="tooltip"
          label="用户类型"
        ></el-table-column>
        <el-table-column
          prop="stateName"
          :show-overflow-tooltip="tooltip"
          label="账号状态"
        ></el-table-column>
        <!-- <el-table-column prop="avatarUrl" width="159" label="头像" align="center">
          <template slot-scope="scope">
            <div class="img" style="cursor:pointer">
              <viewer>
                <img
                  :src="scope.row.avatarUrl"
                  alt
                  :onerror="errImg"
                  title="查看高清图片"
                  style="width: 40px;height: 40px;border-radius: 50%"
                />
              </viewer>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="balance"
          :show-overflow-tooltip="tooltip"
          label="余额"
        ></el-table-column>
        <el-table-column
          prop="spend"
          :show-overflow-tooltip="tooltip"
          label="平台消费"
        ></el-table-column>
        <el-table-column :show-overflow-tooltip="tooltip" label="订单记录">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '1')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <!-- <el-table-column :show-overflow-tooltip="tooltip" label="抽签记录">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '2')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="tooltip" label="拍卖纪录">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '3')"
              >点击查看</el-link
            >
          </template>
        </el-table-column> -->
        <el-table-column :show-overflow-tooltip="tooltip" label="提货券">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '4')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="tooltip" label="优惠券">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '5')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <!-- <el-table-column fixed="right" label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >封号</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 用户添加和用户编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加用户' : '修改用户'"
        :visible.sync="visible"
        @close="onCancel('ruleForm')"
        width="550px"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="120px"
        >
          <el-form-item
            label="用户名称"
            prop="name"
            style="margin-bottom: 30px"
          >
            <el-input
              clearable
              v-model="ruleForm.name"
              placeholder="请输入用户名称"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" style="margin-bottom: 30px">
            <el-input
              type="number"
              clearable
              v-model="ruleForm.phone"
              placeholder="请输入手机号"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            style="margin-bottom: 30px"
            v-if="type == 'add'"
          >
            <el-input
              clearable
              show-password
              v-model="ruleForm.password"
              placeholder="请输入密码"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            style="margin-bottom: 30px"
            v-if="type == 'edit'"
          >
            <el-input
              clearable
              show-password
              v-model="ruleForm.password"
              placeholder="请输入密码(为空不修改)"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="选择角色"
            prop="role_id"
            style="margin-bottom: 30px"
          >
            <el-select
              v-model="ruleForm.role_id"
              clearable
              filterable
              placeholder="请选择角色"
              style="width: 250px"
            >
              <el-option
                v-for="(item, index) in role"
                :key="index"
                :label="item.role_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>
      <el-dialog title="提货券" :visible.sync="dialogVisible" width="70%">
        <el-form :inline="true" :model="tableSearsch" size="small">
          <el-form-item>
            <el-date-picker
              v-model="tableSearsch.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-select
              clearable
              v-model="tableSearsch.source"
              placeholder="购买方式"
            >
              <el-option :label="'购买'" :value="1"> </el-option>
              <el-option :label="'赠送'" :value="2"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="tableSearsch.pickUpStatus"
              placeholder="使用状态"
              clearable
            >
              <el-option :label="'未使用'" :value="1"> </el-option>
              <el-option :label="'已使用'" :value="2"> </el-option>
              <el-option :label="'已赠送'" :value="3"> </el-option>
              <el-option :label="'已邮寄'" :value="4"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" @click="getvoucherList(memberId)"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table :data="pickTableData" stripe style="width: 100%">
          <el-table-column
            prop="goodsName"
            label="商品"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="sourceName"
            label="获取方式"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="orderCode"
            label="订单号"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="sharerName"
            label="分享人"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="获取时间"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="pickUpStatusName"
            label="状态"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="giverName"
            label="赠送人"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="pickUpTime"
            label="使用时间"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
          <el-table-column
            prop="deviceAddress"
            label="取货地点"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>
        </el-table>
        <div class="pageBox">
          <el-pagination
            @current-change="dailogHandleSizeChangeCommi"
            background
            layout="prev, pager, next"
            :total="tableTotal"
          >
          </el-pagination>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="优惠券"
        :visible.sync="discountsDialogVisible"
        width="70%"
      >
        <el-form :inline="true" :model="discountSearsch" size="small">
          <el-form-item>
            <el-date-picker
              v-model="discountSearsch.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button icon="el-icon-search" @click="getdiscountList(memberId)"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          border
          ref="table"
          :data="discountsTableData"
          style="width: 100%"
        >
          <el-table-column prop="petName" label="用户名"></el-table-column>
          <el-table-column
            prop="create_time"
            :show-overflow-tooltip="tooltip"
            label="发放时间"
          ></el-table-column>
          <el-table-column
            prop="usageName"
            :show-overflow-tooltip="tooltip"
            label="状态"
          ></el-table-column>

          <el-table-column
            prop="usage_time"
            width="159"
            label="使用时间"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="goodsName"
            label="使用商品"
            :show-overflow-tooltip="tooltip"
          >
          </el-table-column>

          <el-table-column
            prop="due_date"
            label="有效时间"
            :show-overflow-tooltip="tooltip"
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            :show-overflow-tooltip="tooltip"
          ></el-table-column>
        </el-table>
        <div class="pageBox">
          <el-pagination
            @current-change="discountsHandleSizeChangeCommi"
            background
            layout="prev, pager, next"
            :total="discountsTotal"
          >
          </el-pagination>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="discountsDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  authUserList,
  userAdd,
  userEdit,
  userDel,
  getRole,
  MAIN,
  pickupCode,
  couponRecord,
} from "../../utils/api";

export default {
  name: "AuthUser",
  props: ["height"],
  data() {
    return {
      tableData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
      }, //权限
      tableSearsch: {
        time: "",
        source: "",
        pickUpStatus: "",
      },
      discountsTableData: [],
      discountsTotal: 0,
      memberList: [],
      discountsDialogVisible: false,
      discountSearsch: {
        time: "",
      },
      discountPageNumber: 1,
      pickTableData: [],
      tablePageSize: 10,
      tablePageNumber: 1,
      tableTotal: 0,
      userinfo: {},

      formSearch: {
        name: "",
        phone: "",
        type: "",
      }, //搜索
      dialogVisible: false,
      memberId: "",
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        name: "",
        phone: "",
        password: "",
        role_id: "",
      }, //添加和修改的表单
      rules: {
        name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        role_id: [
          { required: true, message: "请选择所属角色", trigger: "change" },
        ],
      },
      role: {}, //角色下拉列表
    };
  },

  mounted() {
    this.getResource();
  },
  methods: {
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增用户 82
      // 修改用户 83
      // 删除用户 84
      if (arr.indexOf("82") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("83") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("84") > -1) {
        this.permission.del = true;
      }

      this.getData();
      this.getRole(); //角色下拉列表
    },
    // 角色下拉列表
    getRole() {
      this.postRequest(getRole, {}, MAIN).then((res) => {
        if (res.code == 200) {
          this.role = res.data;
        }
      });
    },
    dailogHandleSizeChangeCommi(val) {
      this.tablePageNumber = val;
      this.getvoucherList(this.memberId);
    },
    discountsHandleSizeChangeCommi() {
      this.discountPageNumber = val;
      this.getdiscountList(this.memberId);
    },
    // 获取优惠券+
    getdiscountList(id) {
      let start_time, end_time;
      if (
        this.discountSearsch.time != "" &&
        this.discountSearsch.time != null
      ) {
        start_time = this.discountSearsch.time[0] + " 00:00:00";
        end_time = this.discountSearsch.time[1] + " 23:59:59";
      }
      let params = {
        pageSize: this.pageSize,
        pageNumber: this.discountPageNumber,
        start_time,
        end_time,
        memberId: id,
      };
      this.postRequest(couponRecord, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.discountsTableData = res.data.list;
          this.discountsTotal = res.data.count;
        }
      });
    },
    // 获取提货券
    getvoucherList(id) {
      let start_time, end_time;
      if (this.tableSearsch.time != "" && this.tableSearsch.time != null) {
        start_time = this.tableSearsch.time[0] + " 00:00:00";
        end_time = this.tableSearsch.time[1] + " 23:59:59";
      }

      let params = {
        pageSize: this.tablePageSize,
        pageNumber: this.tablePageNumber,
        memberId: id,
        start_time,
        end_time,
        source: this.tableSearsch.source,
        pickUpStatus: this.tableSearsch.pickUpStatus,
      };
      this.postRequest(pickupCode, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.pickTableData = res.data.list;
          this.tableTotal = res.data.count;
        }
      });
    },
    // 点击查看
    examineClick(row, type) {
      switch (type) {
        case "1":
          this.$router.push({
            name: "DeliverOrders",
            query: {
              memberId: row.id,
            },
          });
          break;
        case "2":
          // this.$router.push({
          //   name: "LockerList",
          //   query: {
          //     agentId: row.id,
          //   },
          // });
          break;
        case "3":
          // this.$router.push({
          //   name: "DeliverOrders",
          //   query: {
          //     agentId: row.id,
          //   },
          // });
          break;
        case "4":
          this.dialogVisible = true;
          this.memberId = row.id;
          this.getvoucherList(row.id);
          break;
        case "5":
          this.discountsDialogVisible = true;
          this.getdiscountList(row.id);
          break;
      }
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        petName: this.formSearch.name,
        phone: this.formSearch.phone,
        state: this.formSearch.type,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      };
      this.postRequest(authUserList, params, MAIN).then((res) => {
        if (res.code == 200) {
          console.log(res.data);
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.currentRow = row;
      this.visible = true;
      this.ruleForm = {
        name: row.name,
        phone: row.phone,
        password: row.password,
        role_id: row.role_id,
      };
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userinfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(userDel, parm, MAIN).then((res) => {
          // console.log(res);
          if (res.code == 200) {
            this.$notify({
              title: "删除成功",
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      }).catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.userAdd();
          } else if (this.type == "edit") {
            this.userEdit();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    userAdd() {
      console.log(this.ruleForm.type);
      let params = {
        name: this.ruleForm.name,
        phone: this.ruleForm.phone,
        password: this.ruleForm.password,
        role_id: this.ruleForm.role_id,
        userId: this.userinfo.id,
      };

      this.postRequest(userAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    userEdit() {
      let params = {
        id: this.currentRow.id,
        name: this.ruleForm.name,
        phone: this.ruleForm.phone,
        password: this.ruleForm.password,
        role_id: this.ruleForm.role_id,
        userId: this.userinfo.id,
      };

      this.postRequest(userEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      this.confirmLoading = false;
      this.ruleForm = {
        name: "",
        phone: "",
        password: "",
        role_id: "",
      };
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
.pageBox {
  margin-top: 20px;
}
</style>
